package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.seckill.TbSeckillGoods;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.service.seckill.SeckillService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 秒杀
 * @Author Eayon
 * @Date 2020/3/17 11:05
 */
@Controller
@RequestMapping("seckill")
public class SeckillController {

    @Reference(check = false)
    private SeckillService seckillService;

    Logger log = LoggerFactory.getLogger(SeckillController.class);

    /**
     * 跳转秒杀列表页 并携带所有状态良好的秒杀商品信息集合
     * @return
     */
    @RequestMapping("index")
    public String index(Model model){
        //查询所有状态正常，库存正常，时间正常的秒杀商品
        List<TbSeckillGoods> seckillGoodsList = seckillService.findSeckillGoodsAll();
        model.addAttribute("seckillGoodsList",seckillGoodsList);
        return "seckill/seckill-index";
    }


    /**
     * 根据秒杀商品id查询秒杀商品信息并跳转秒杀商品详情页
     * @param id
     */
    @RequestMapping("getSeckillById/{id}")
    public String getSeckillById(@PathVariable("id") Long id,Model model){
        TbSeckillGoods seckillGoods = seckillService.getSeckillById(id);
        //如果该商品不存在的话就跳转错误提示页面
        if(seckillGoods==null){
            return "seckill-over";
        }
        model.addAttribute("seckillGoods",seckillGoods);
        return "seckill/seckill-item";
    }

    /**
     * 秒杀提交订单
     * @return
     */
    @RequestMapping("submitOrder")
    @ResponseBody
    public DataResult submitOrder(Long seckillId){
        //判断用户是否登录
        TbUser user = (TbUser)SecurityUtils.getSubject().getPrincipal();
        if(user==null){
            return new DataResult(501,"用户未登录");
        }
        //如果登录获取用户id添加订单
        Long userId = user.getId();
        try {
            seckillService.submitOrder(seckillId,userId);
        }catch (RuntimeException e){
            log.error("异常"+e);
            return new DataResult(500,e.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),"抢购成功，等待付款");
    }
}
